#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/wait.h>
#include <fcntl.h>

int main() {
    int fd[2];
    pid_t pid;
    char buffer[1024];

    // 创建管道
    if (pipe(fd) < 0) {
        fprintf(stderr, "Failed to create pipe.\n");
        return -1;
    }

    // 创建子进程
    if ((pid = fork()) < 0) {
        fprintf(stderr, "Failed to create child process.\n");
        return -1;
    } else if (pid == 0) {
        // 子进程读取文件并将结果写入管道
        close(fd[0]);
        int file_fd = open("file.txt", O_RDONLY);
        ssize_t num_read = read(file_fd, buffer, sizeof(buffer));
        close(file_fd);
        write(fd[1], buffer, num_read);
        close(fd[1]);
        printf("child success\n");
        _exit(0);
    } else {
        // 父进程等待子进程读取完文件后再执行
        close(fd[1]);
        wait(NULL);
        ssize_t num_read = read(fd[0], buffer, sizeof(buffer));
        close(fd[0]);
        printf("father success\n");
        printf("%.*s\n", (int)num_read, buffer);
    }

    return 0;
}
